package com.wnhz.work.jy.fragment;


import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.activity.LoginActivity;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.MyUtils;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * ----注册
 */
public class SignFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "SignFragment";
    private View view;
    private TextView tv_agreement;
    private String APP_ID = "wx054406f5ccd828da";

    private EditText et_phone, et_code, et_passWord, et_invitation, et_passWord_true;
    private String phoneNumber;
    private String password;
    private String password_two;
    private String code;
    private String invitationCode;
    private TextView tv_gain;

    private int time = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 54:
                    time--;
                    if (time == 0) {
                        tv_gain.setText("获取验证码");
                    } else {
                        tv_gain.setText("获取验证码" + time + "s");
                        handler.sendEmptyMessageDelayed(54, 1000);
                    }
                    break;
            }
        }
    };

    private LoginActivity loginActivity;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_sign, container, false);
        loginActivity = (LoginActivity) getActivity();
        initView();
        return view;
    }

    private void initView() {

        tv_gain = (TextView) view.findViewById(R.id.tv_gain);
        et_phone = (EditText) view.findViewById(R.id.et_phone);
        et_code = (EditText) view.findViewById(R.id.et_code);
        et_passWord = (EditText) view.findViewById(R.id.et_passWord);
        et_passWord_true = (EditText) view.findViewById(R.id.et_passWord_true);
        et_invitation = (EditText) view.findViewById(R.id.et_invitation);
        tv_agreement = (TextView) view.findViewById(R.id.tv_agreement);

        SpannableString text = new SpannableString("*注册/登录表示你已同意《嘉轶金服服务协议》");
        text.setSpan(new ForegroundColorSpan(0xffff3c3d), 12, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_agreement.setText(text);
        tv_agreement.setOnClickListener(this);
        view.findViewById(R.id.tv_sign).setOnClickListener(this);
        view.findViewById(R.id.iv_weixin).setOnClickListener(this);
        view.findViewById(R.id.iv_weibo).setOnClickListener(this);
        view.findViewById(R.id.iv_qq).setOnClickListener(this);
        view.findViewById(R.id.tv_gain).setOnClickListener(this);
        view.findViewById(R.id.scan_code).setOnClickListener(this);
    }

    private IWXAPI api;

    public void setet_invitation(String s) {
        et_invitation.setText(s);
    }

    @Override
    public void onResume() {
        super.onResume();
        //loginActivity.closeDialog();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //注册
            case R.id.tv_sign:
                invitationCode = et_invitation.getText().toString();
                password = et_passWord.getText().toString();
                password_two = et_passWord_true.getText().toString();
                code = et_code.getText().toString();
                phoneNumber = et_phone.getText().toString();
                if (!MyUtils.isMobileNO(phoneNumber)) {
                    myToast("请输入正确手机号");
                } else if (code == null || "".equals(code)) {
                    myToast("请输入验证码");
                } else if (!phoneNumber.equals(oldphone)) {
                    myToast("验证码与手机号不匹配");
                } else if (!code.equals(first_code)) {
                    myToast("验证码错误");
                } else if (password.length() < 6) {
                    myToast("密码不能少于6位");
                } else if (password_two.length() < 6) {
                    myToast("密码不能少于6位");
                } else if (!password.equals(password_two)) {
                    myToast("两次输入的密码不一致");
                }else {
                    sign();
                }
                /*if (MyApplication.getInstance().bean == null){
                    getWX();
                }else {

                }*/


                break;

            //微信登录
            case R.id.iv_weixin:
                getWX();

                break;
            case R.id.tv_gain:
                phoneNumber = et_phone.getText().toString();
                if (MyUtils.isMobileNO(phoneNumber)) {
                    if (time == 0) {
                        tv_gain.setClickable(false);
                        getCode(phoneNumber);
                    }
                }

                break;

          /*  //微博登录
            case R.id.iv_weibo:
                Toast.makeText(getActivity(), "微博登录", Toast.LENGTH_SHORT).show();
                break;*/

           /* //QQ登录
            case R.id.iv_qq:
                Toast.makeText(getActivity(), "QQ登录", Toast.LENGTH_SHORT).show();
                break;*/

            //扫码
            case R.id.scan_code:
                loginActivity.scanCode();
                break;
            case R.id.tv_agreement:
                loginActivity.agreement();
                break;

            default:
                break;
        }
    }

    private void getWX() {
        loginActivity.showDialog();
        if (api == null) {
            api = WXAPIFactory.createWXAPI(getActivity(), APP_ID, false);
            //api.openWXApp();
            api.registerApp(APP_ID);
        }
        if (!api.isWXAppInstalled()) {
            //提醒用户没有按照微信
            Toast.makeText(getActivity(), "没有安装微信,请先安装微信!", Toast.LENGTH_SHORT).show();
            return;
        }

        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }

    private void myToast(String s) {
        Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
    }

    private String oldphone;
    private String codetime;
    private String first_code;

    private void getCode(String phoneNumber) {
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNumber", phoneNumber);
        loginActivity.showDialog();
        XUtil.Post(ConfigUtil.GETYZM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.d(TAG, "onSuccess: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)) {
                        JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                        oldphone = jsonObject1.optString("phone");
                        codetime = jsonObject1.optString("time");
                        first_code = jsonObject1.optString("code");
                        time = 60;
                        handler.sendEmptyMessage(54);
                    } else {
                        String info = jsonObject.optString("info");
                        Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                tv_gain.setClickable(true);
                loginActivity.closeDialog();
            }
        });

    }

    private void sign() {
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNumber", phoneNumber);

        map.put("password", password);
        map.put("codeIstrue", code);
        map.put("oldphone", phoneNumber);
        map.put("codetime", codetime);

        if (invitationCode != null && !"".equals(invitationCode)) {
            map.put("invitationCode", invitationCode);
        }

        if (MyApplication.getInstance().bean == null) {
            MyApplication.getInstance().sign_map = map;
            getWX();
            return;
        } else {
            map.put("userName", MyApplication.getInstance().bean.getNickname());
            map.put("userImg", MyApplication.getInstance().bean.getHeadimgurl());
            map.put("openId", MyApplication.getInstance().bean.getOpenid());
            map.put("unionId", MyApplication.getInstance().bean.getUnionid());
        }
        loginActivity.showDialog();
        XUtil.Post(ConfigUtil.REGISTER_NORMAL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess:sign " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)) {
                        MyApplication.getInstance().sign_map = null;
                    }
                    String info = jsonObject.optString("info");
                    Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                loginActivity.closeDialog();
            }
        });

    }

    @Override
    public void onDestroy() {
        MyApplication.getInstance().sign_map = null;
        super.onDestroy();
    }
}
